﻿
namespace Mulala.Cavan.Core.Persistent
{
    using System;
    using System.Collections.Generic;
    using System.Diagnostics.Contracts;
    using System.Linq;
    using Mulala.Cavan.Core.Settings;

    /// <summary>
    ///     Extends SearchObject with Templated Example property
    /// </summary>
    /// <typeparam name = "T"></typeparam>
    /// <typeparam name = "TID"></typeparam>
    [Serializable]
    public abstract class Search<TID> : ISearch<TID>
    {
        #region members
        IDictionary<string, bool> _orderBy = new Dictionary<string, bool>();
        #endregion members

        #region constructor
        /// <summary>
        ///     Resets the default ListRowCount based on Web.config.
        ///     It could be reset ad hoc using the MaxRowsPerPage property
        /// </summary>
        protected Search()
        {
            MaxRowsPerPage = Global.Settings.MaxRowsPerPage;
            CurrentPage = 1;
        }
        #endregion constructor

        #region properties
        /// <summary>
        ///     DO NOT FILL !!!
        ///     Dao will fill this value. 
        ///     Total count of all rows matching searching criteria.
        ///     DO NOT USE !!!
        /// </summary>
        public virtual long TotalRowCount { get; set; }

        /// <summary>
        ///     SET Maximum rows count on a page. 
        ///     In fact this value is always set, by default to 20.
        ///     In cases when the target is to find any - set it to 1.
        ///     When you want all records, set it to int.MaxValue
        /// </summary>
        public virtual int MaxRowsPerPage { get; set; }

        /// <summary>
        ///     Paging. This value is maintained by base controller
        ///     and keeps information about which is the currently navigated page
        /// </summary>
        public virtual int CurrentPage { get; set; }

        /// <summary>
        ///     Keeps the current Item number (position in the list)
        ///     to allow paging base on single Item!
        /// </summary>
        public virtual int CurrentRow { get; set; }

        /// <summary>
        ///     The counted value! Allows to display on UI how many pages is in the storage
        /// </summary>
        public virtual long PageCount
        {
            get { return (TotalRowCount - 1) / MaxRowsPerPage; }
        }

        /// <summary>
        ///     Tricky collection allowing sorting. 
        ///     If the implementing collection is Dictionary[string, bool]
        ///     then even the position plays role.
        ///     The first added as firstly evaluated in the ORDER BY clause.
        /// </summary>
        public virtual IDictionary<string, bool> OrderBy
        {
            get { return _orderBy; }
            set { _orderBy = value; }
        }

        public virtual TID ID { get; set; }
        #endregion properties
    }
}